<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-包装返工单`"
		width="1000px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="110px" :show-message="false">
			<div ref="box1">
				<jk-card>
					<el-row ref="box1" class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="单据编号">
								<span class="read-only-2">{{ ruleForm.code || '系统自动生成' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="下单日期" prop="belongDate">
								<span v-if="pageType === 'detail' || ruleForm.auditState >= 1" class="read-only-2">{{ ruleForm.belongDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.belongDate" :clearable="true" size="medium" placehpreer="" @change="onDateChange" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" :label="ruleForm.type === 1 ? '返工日期' : '改包装日期'" prop="changeDate">
								<span v-if="pageType === 'detail' || ruleForm.auditState >= 1" class="read-only-2">{{ ruleForm.changeDate }}</span>
								<jk-date-picker v-else v-model="ruleForm.changeDate" :picker-options="pickerOptions" :clearable="true" size="medium" placehpreer="" />
							</el-form-item>
						</el-col>

						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="计划数量" prop="planQty">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.planQty }}</span>
								<jk-number-input v-else v-model="ruleForm.planQty" size="medium" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="打包数量" prop="packQty">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.packQty }}</span>
								<jk-number-input v-else v-model="ruleForm.packQty" size="medium" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="报工数量" prop="packReportQty">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.packReportQty }}</span>
								<jk-number-input v-else v-model="ruleForm.packReportQty" size="medium" />
							</el-form-item>
						</el-col>
						<el-col v-if="ruleForm.empName" :span="8">
							<el-form-item class="margin-bottom-0" label="下单人">
								<span class="read-only-2">{{ ruleForm.empName }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="16">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState >= 1" class="read-only-2">{{ ruleForm.remark }}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placehpreer="" />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
				<jk-divider-card title="原品种" class="margin-top-30" icon="el-icon-news" :title-style="{ color: '#2d8cf0' }" :style="{ borderColor: '#2d8cf0' }">
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="品种" prop="preProductId">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.preProductName }}</span>
								<jk-button v-else type="primary" @click="selectDialogState = true">
									<span class="item-gap">{{ ruleForm.preProductName || '选择' }}</span>
									<span class="el-icon-edit"></span>
								</jk-button>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="批号">
								<span class="read-only-2">{{ ruleForm.preBatchCode }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="纸管颜色" prop="prePaperTubeList">
								<!--								<span class="read-only-2">{{ filterColor(ruleForm.prePaperTubeList) }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ filterColor(ruleForm.prePaperTubeList) }}</span>
								<checkboxPopover
									v-else
									title="纸管颜色"
									:default-list.sync="ruleForm.prePaperTubeList"
									:option-list="ltColorList"
								></checkboxPopover>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="腰绳颜色" prop="preWaistPopeList">
								<!--								<span class="read-only-2">{{ filterColor(ruleForm.preWaistPopeList) }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ filterColor(ruleForm.preWaistPopeList) }}</span>
								<checkboxPopover
									v-else
									title="腰绳颜色"
									:default-list.sync="ruleForm.preWaistPopeList"
									:option-list="waistPopeList"
								></checkboxPopover>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="标签颜色" prop="preLabelColorList">
								<!--								<span class="read-only-2">{{ filterColor(ruleForm.preLabelColorList) }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ filterColor(ruleForm.preLabelColorList) }}</span>
								<checkboxPopover
									v-else
									title="标签颜色"
									:default-list.sync="ruleForm.preLabelColorList"
									:option-list="labelColorList"
								></checkboxPopover>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="计划包数" prop="packNumOld">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.packNumOld }}</span>
								<jk-number-input v-else v-model="ruleForm.packNumOld" @change="onPackNumOldChange"></jk-number-input>
							</el-form-item>
						</el-col>

						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="活码数" prop="liveCodeNumOld">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.liveCodeNumOld }}</span>
								<jk-number-input v-else v-model="ruleForm.liveCodeNumOld"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="活码公斤数" prop="liveCodeOld">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.liveCodeOld }}</span>
								<jk-number-input v-else v-model="ruleForm.liveCodeOld" @change="onLiveCodeOldChange"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="总公斤数" prop="allQtyOld">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.allQtyOld }}</span>
								<jk-number-input v-else v-model="ruleForm.allQtyOld"></jk-number-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-divider-card>
				<jk-divider-card title="包装后品种" class="margin-top-30" icon="el-icon-postcard" :title-style="{ color: '#19be6b' }" :style="{ borderColor: '#19be6b' }">
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="品种" prop="productId">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.productName }}</span>
								<remote-search-product-input
									v-else
									placeholder="品种"
									default-stock-type="FINISHED_PRODUCT"
									only-key="productId"
									query-name="productName"
									:form-data="ruleForm"
									@on-select="onSelectProductChange"
								></remote-search-product-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="批号">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.batchCode }}</span>
								<jk-button v-else :disabled="!ruleForm.productName" type="success" @click="selectBatchCodeDialogState = true">
									<span class="item-gap">{{ ruleForm.batchCode || '选择' }}</span>
									<span class="el-icon-edit"></span>
								</jk-button>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="纸管颜色" prop="paperTubeList">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ filterColor(ruleForm.paperTubeList) }}</span>
								<checkboxPopover
									v-else
									title="纸管颜色"
									:default-list.sync="ruleForm.paperTubeList"
									:option-list="ltColorList"
								></checkboxPopover>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="腰绳颜色" prop="waistPopeList">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ filterColor(ruleForm.waistPopeList) }}</span>
								<checkboxPopover
									v-else
									title="腰绳颜色"
									:default-list.sync="ruleForm.waistPopeList"
									:option-list="waistPopeList"
								></checkboxPopover>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="标签颜色" prop="labelColorList">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ filterColor(ruleForm.labelColorList) }}</span>
								<checkboxPopover
									v-else
									title="标签颜色"
									:default-list.sync="ruleForm.labelColorList"
									:option-list="labelColorList"
								></checkboxPopover>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="包数" prop="packNumNew">
								<!--								<span class="read-only-2">{{ ruleForm.packNumNew }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.packNumNew }}</span>
								<jk-number-input v-else v-model="ruleForm.packNumNew" @change="onPackNumNewChange"></jk-number-input>
							</el-form-item>
						</el-col>

						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="活码数" prop="liveCodeNumNew">
								<!--								<span class="read-only-2">{{ ruleForm.liveCodeNumNew }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.liveCodeNumNew }}</span>
								<jk-number-input v-else v-model="ruleForm.liveCodeNumNew"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="活码公斤数" prop="liveCodeNew">
								<!--								<span class="read-only-2">{{ ruleForm.liveCodeNew }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.liveCodeNew }}</span>
								<jk-number-input v-else v-model="ruleForm.liveCodeNew" @change="onLiveCodeNewChange"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="总公斤数" prop="allQtyNew">
								<!--								<span class="read-only-2">{{ ruleForm.allQtyNew }}</span>-->
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.allQtyNew }}</span>
								<jk-number-input v-else v-model="ruleForm.allQtyNew"></jk-number-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-divider-card>
			</div>
		</el-form>

		<radio-select-dialog
			:dialog-state="selectDialogState"
			:type="ruleForm.type"
			@on-confirm="onConfirmBtnOfSelectDialog"
			@on-visible-change="onVisibleChangeOfSelectDialog"
		></radio-select-dialog>

		<select-batch-code-dialog
			:selected-list="[]"
			:form-data="ruleForm"
			api-must-query-prefix="product"
			:dialog-state="selectBatchCodeDialogState"
			@on-visible-change="onVisibleChangeOfSelectBatchCodeDialog"
			@on-confirm="onConfirmBtnOfSelectBatchCodeDialog"
		></select-batch-code-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionChangeProductRecordCreate,
        productionChangeProductRecordUpdate,
        productionChangeProductRecordGet
    } from '../../../api/production/xsNotice';
    import { formatDate } from '../../../utils/jk/jk-tool';
    import remoteSearchBatchCodeInput
        from '../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import checkboxPopover from '../order/components/form-box/checkbox-popover';
    import getTubeColor from '../foreSpinPrd/foreSpinningPlan/components/form-box/get-tube-color';
    import { spinTubeColorPage } from '../../../api/basicData/tubeColor';
    import { validateArr } from '../../../utils/jk/validator';
    import selectBatchCodeDialog from '../order/components/form-box/radio-select-batch-code-dialog';
    import remoteSearchProductInput from '../order/components/remote-search-product-input';
    import radioSelectDialog from './components/radio-select-notice-dialog';
    export default {
        mixins: [calHeight, getTubeColor],
        components: {
            radioSelectDialog,
            selectBatchCodeDialog,
            checkboxPopover,
            remoteSearchBatchCodeInput,
            remoteSearchProductInput
        },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data(_this) {
            return {
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.parse(_this.ruleForm.belongDate) - (24 * 60 * 60 * 1000);
                    }
                },
                selectBatchCodeDialogState: false,
                selectDialogState: false,
                tableLoading: false,
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'belongDate': '',
                    'changeDate': '',
                    'type': 1, // 0: 改包装通知单; 1:包装返工单
                    'preProductId': null,
                    'preProductCode': '',
                    'preProductName': '',
                    'productId': null,
                    'productCode': '',
                    'productName': '',
                    'remark': '',
                    'liveCodeNumOld': 0,
                    'allQtyOld': 0,
                    'packNumOld': 0,
                    'liveCodeOld': 0,
                    'packNumNew': 0,
                    'liveCodeNumNew': 0,
                    'liveCodeNew': 0,
                    'allQtyNew': 0,
                    'packReportQty': null,
                    'preBatchId': '',
                    'preBatchCode': '',
                    'batchId': '',
                    'batchCode': '',
                    'planQty': null,
                    'packQty': null,
                    'prePaperTubeList': [],
                    'preWaistPopeList': [],
                    'preLabelColorList': [],
                    'paperTubeList': [],
                    'waistPopeList': [],
                    'labelColorList': []
                },
                rules: {
                    productId: [{ required: true, trigger: 'change' }],
                    planQty: [{ required: true, trigger: 'change' }],
                    packQty: [{ required: true, trigger: 'change' }],
                    packReportQty: [{ required: true, trigger: 'change' }],
                    changeDate: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    preProductId: [{ required: true, trigger: 'change' }],
                    paperTubeList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    waistPopeList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    labelColorList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    prePaperTubeList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    preWaistPopeList: [{ required: true, validator: validateArr, trigger: 'change' }],
                    preLabelColorList: [{ required: true, validator: validateArr, trigger: 'change' }]
                },
                waistPopeList: [],
                labelColorList: []
            };
        },
        methods: {
            onPackNumOldChange(packNumOld) {
                this.$set(this.ruleForm, 'allQtyOld', packNumOld * 25 + this.ruleForm.liveCodeOld);
            },
            onLiveCodeOldChange(liveCodeOld) {
                this.$set(this.ruleForm, 'allQtyOld', this.ruleForm.packNumOld * 25 + liveCodeOld);
            },
            onPackNumNewChange(packNumNew) {
                this.$set(this.ruleForm, 'allQtyNew', packNumNew * 25 + this.ruleForm.liveCodeNew);
            },
            onLiveCodeNewChange(liveCodeNew) {
                this.$set(this.ruleForm, 'allQtyNew', this.ruleForm.packNumNew * 25 + liveCodeNew);
            },
            onSelectProductChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'batchId', null);
                    this.$set(this.ruleForm, 'batchCode', '');

                    this.$set(this.ruleForm, 'productId', e.id);
                    this.$set(this.ruleForm, 'productCode', e.code);
                    this.$set(this.ruleForm, 'productName', e.name);
                    this.$set(this.ruleForm, 'productModels', e.models);
                }
            },
            onVisibleChangeOfSelectBatchCodeDialog(e) {
                this.selectBatchCodeDialogState = e;
            },
            onConfirmBtnOfSelectBatchCodeDialog(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'batchId', e.id);
                    this.$set(this.ruleForm, 'batchCode', e.batchCode);
                }
                this.selectBatchCodeDialogState = false;
            },
            onSelectBatchCodeChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'batchCode', e.batchCode);
                    this.$set(this.ruleForm, 'productId', e.productId);
                    this.$set(this.ruleForm, 'productCode', e.productCode);
                    this.$set(this.ruleForm, 'productName', e.productName);
                }
            },
            filterColor(list) {
                const arr = list.filter(x => x.auditState);
                const str = arr.map(x => x.name).join(',');
                return str;
            },
            onSelectBatchCodeBtn(index) {
                this.editRowIndex = index;
                this.selectDialogState = true;
            },
            onConfirmBtnOfSelectDialog(e) {
                this.$set(this.ruleForm, 'preBatchId', e.batchId);
                this.$set(this.ruleForm, 'preBatchCode', e.batchCode);
                this.$set(this.ruleForm, 'batchId', e.batchId);
                this.$set(this.ruleForm, 'batchCode', e.batchCode);

                this.$set(this.ruleForm, 'preProductId', e.inventoryId);
                this.$set(this.ruleForm, 'preProductCode', e.productCode);
                this.$set(this.ruleForm, 'preProductName', e.inventoryName);
                this.$set(this.ruleForm, 'preProductModels', e.productModels);

                this.$set(this.ruleForm, 'productId', e.inventoryId);
                this.$set(this.ruleForm, 'productCode', e.productCode);
                this.$set(this.ruleForm, 'productName', e.inventoryName);
                this.$set(this.ruleForm, 'productModels', e.productModels);

                this.$set(this.ruleForm, 'prdNoticeCode', e.code);
                this.$set(this.ruleForm, 'prdNoticeId', e.id);
                this.$set(this.ruleForm, 'productOrderCode', e.productOrderCode);
                this.$set(this.ruleForm, 'productOrderId', e.productOrderId);

                // this.$set(this.ruleForm, 'prePaperTubeList', e.orderBatch ? e.orderBatch.paperTubeList : []);
                // this.$set(this.ruleForm, 'preWaistPopeList', e.orderBatch ? e.orderBatch.waistPopeList : []);
                // this.$set(this.ruleForm, 'preLabelColorList', e.orderBatch ? e.orderBatch.labelColorList : []);
                //
                // this.$set(this.ruleForm, 'paperTubeList', e.orderBatch ? e.orderBatch.paperTubeList : []);
                // this.$set(this.ruleForm, 'waistPopeList', e.orderBatch ? e.orderBatch.waistPopeList : []);
                // this.$set(this.ruleForm, 'labelColorList', e.orderBatch ? e.orderBatch.labelColorList : []);
                this.selectDialogState = false;
            },
            onVisibleChangeOfSelectDialog(e) {
                this.selectDialogState = e;
            },
            onDateChange(e) {
                this.$set(this.ruleForm, 'changeDate', e ? formatDate(e) : '');
            },
            onDeleteBtn(scope) {
                this.ruleForm.itemList.splice(scope.rowIndex, 1);
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    delete params.id;
                }
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? productionChangeProductRecordCreate : productionChangeProductRecordUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return productionChangeProductRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.itemList = resData.itemList || [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getWaistPopeListRequest() {
                return spinTubeColorPage({ typeCode: 'WAIST_CORD_COLOR' }).then(res => {
                    if (res.data.status === 200) {
                        this.waistPopeList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            getLabelColorListRequest() {
                return spinTubeColorPage({ typeCode: 'LABEL_COLOR_LIST' }).then(res => {
                    if (res.data.status === 200) {
                        this.labelColorList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'changeDate', formatDate(Date.now()));
                }
                await this.getWaistPopeListRequest();
                await this.getLabelColorListRequest();
                await this.getLtColorListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
